from dateutil import parser

from dateutil import parser
from datetime import datetime


def get_seconds_diff(t1, t2):
    # 获得两时间间隔`t1 - t2`
    if isinstance(t1, str):
        datetime1 = parser.parse(t1)
    else:
        datetime1 = datetime.fromtimestamp(t1)

    if isinstance(t2, str):
        datetime2 = parser.parse(t2)
    else:
        datetime2 = datetime.fromtimestamp(t2)

    time_diff = datetime1 - datetime2

    return time_diff.total_seconds()


def format_duration(seconds, length=None):
    assert seconds > 0

    intervals = [
        ('年', 60 * 60 * 24 * 365),
        ('月', 60 * 60 * 24 * 30),
        ('周', 60 * 60 * 24 * 7),
        ('天', 60 * 60 * 24),
        ('小时', 60 * 60),
        ('分', 60),
        ('秒', 1)
    ]

    result = []

    for name, count in intervals:
        value = seconds // count
        if value:
            seconds -= value * count
            result.append(f"{value:g}{name}")

    if length is not None:
        result = result[:length]

    return ''.join(result) if result else f'{seconds}'


if __name__ == '__main__':
    from bdtime import tt
    t1 = tt.get_current_beijing_time_str()
    tt.sleep(0.5)
    t2 = tt.get_current_beijing_time_str()
    seconds = get_seconds_diff(t2, t1)
    duration = format_duration(seconds)
    print('seconds:', seconds, " --- duration:", duration)
